import HttpClient, { BaseInterceptor } from "@/common/https/http"

export default () => {
	HttpClient.base = 'https://online-edu-test.mfy777.com/api/user'  // 请求域名
	// HttpClient.base = 'https://ycsj.online.mfy777.com/api/user'  // 请求域名
	// HttpClient.base = 'http://test.deepinfo.cn:9800/api/user'  // 请求域名
	HttpClient.interceptorList = [  // 重写拦截器
		new AuthInterceptor(),
		// new LogInterceptor(),
		new ReponseInterceptor(),
	]
	
	// uni.$http = HttpClient
	return HttpClient;
}


class AuthInterceptor extends BaseInterceptor {  // 登录鉴权
	async request(options) {
		const { user } = uni.$store()
		// console.log('请求token', token, options)
		if (user.token && options.auth) options.header = { ...options.header, "Authorization": user.token }
		return options
	}
}

class LogInterceptor extends BaseInterceptor {  // 日志
	async request(options) {
		console.table([options])
		return options
	}
	
	async reponse(options, reponse) {
		console.table([reponse])
		return reponse
	}
}


const tologinAndMessage = (title, user) => {
	user.signoutFun();
	uni.$fui.href('/pages/account/login');
	uni.showToast({ icon: 'none', title });
	uni?.hideLoading?.();
};

class ReponseInterceptor extends BaseInterceptor {  // reponse 拦截器
	async reponse({ rawResponse, catchResponse, }, { statusCode, data }) {
		const { user } = uni.$store();
		
		try {
			if (statusCode != 200) throw Error("网络请求异常")
			switch(data.error) {
				case 500: 
					throw Error(data.message);
					
				case 401: 
				case 402: 
				case 403: 
				case 406:
					throw Error(data.error) 
			} 
			
			if (rawResponse) return data
			return data.data
			
		} catch(error) {
			switch(+error.message) {
				case 401: 
					tologinAndMessage('账号不存在或已被禁用~', user);
					break;
				 
				case 402: 
					tologinAndMessage('登录失效，请重新登录~', user);
					break;
				 
				case 403: 
					tologinAndMessage('无权限访问~', user);
					break;
				
				case 406:
					tologinAndMessage('您的账号异地登录，请重新登录~', user);
					break;
					
				
				default: 
					uni?.hideLoading?.();
					uni.showModal({ content: error.message, showCancel: false });
					break;
			};
			
			uni?.hideLoading?.();
			throw Error(error);
		};
	};
};